package com.ybwh.springboot2.common.mybatis.plugin.sass.schema;

import com.alibaba.druid.DbType;
import com.alibaba.druid.sql.SQLUtils;
import com.alibaba.druid.sql.ast.SQLStatement;
import com.alibaba.druid.sql.ast.statement.SQLExprTableSource;
import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlASTVisitorAdapter;
import com.alibaba.druid.util.JdbcConstants;
import com.ybwh.springboot2.common.mybatis.plugin.sass.AbstractSassInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;

import java.util.List;

@Slf4j
@Intercepts({
        @Signature(type = Executor.class, method = "query",
                args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}),
        @Signature(type = Executor.class, method = "query",
                args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class}),
        @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class}),})
public class SassSchemaInterceptor extends AbstractSassInterceptor {


    /**
     * @param ignoreTables 忽略的表,多个表用逗号隔开
     */
    public SassSchemaInterceptor(String ignoreTables) {
        super(ignoreTables);
    }


    @Override
    protected String reWriteSql(String sql, String tenantId) {
        return reWriteTableName(sql, tenantId);
    }


    private String reWriteTableName(String sql, String tenantId) {
        DbType dbType = JdbcConstants.MYSQL;
        List<SQLStatement> stmtList = SQLUtils.parseStatements(sql, dbType);
        MySqlASTVisitorAdapter visitor = new MySqlASTVisitorAdapter() {
            @Override
            public boolean visit(SQLExprTableSource x) {
                String tableName = x.getExpr().toString();
                if (IGNORE_TABLES.contains(tableName)) {
                    return true;
                }

                if (StringUtils.isBlank(tenantId)) {
                    log.error("can not get tenantId for table {},sql:{}", tableName, sql);
                    throw new IllegalStateException("can not get tenantId for table " + tableName);
                }

                String suffix = tenantId;
                log.info("-------------tableName:{},suffix={}", tableName, suffix);
                if (StringUtils.isBlank(suffix)) {
                    return true;
                }
                x.setExpr(tableName + "_" + suffix);
                return true;
            }
        };

        for (SQLStatement stmt : stmtList) {
            stmt.accept(visitor);
        }
        String result = SQLUtils.toSQLString(stmtList, dbType);

        return result;
    }
}